#include "Song.h"
#include <QMediaPlayer>
#include <QMediaMetaData>
Song::Song(QString songName, QString artistName, QUrl url, unsigned int id):
    songName(songName), artistName(artistName), url(url), id(id)
{

}

Song::Song(QUrl url):url(url)
{
    QMediaPlayer t;
    t.setMedia(url);
    QString title = t.metaData(QMediaMetaData::Title).toString();
    if (title.isEmpty()) {
    title = t.metaData(QMediaMetaData::AlbumTitle).toString();
        if (title.isEmpty())
            title = "未知";
    }
    QString name = t.metaData(QMediaMetaData::Author).toString();
    if (name.isEmpty()) {
    name = t.metaData(QMediaMetaData::AlbumArtist).toString();
        if (name.isEmpty())
            name = "未知";
    }
    songName = title;
    artistName = name;
    id = 0;
}

void Song::appendToTable(QTableWidget *tb)
{
    // tb->setColumnCount(2);
    int nRow = tb->rowCount();
    tb->insertRow(nRow);
    auto songNameItem = new QTableWidgetItem(songName);
    songNameItem->setData(Qt::UserRole, id);
    songNameItem->setData(Qt::UserRole + 1, url);
    tb->setItem(nRow, 0, songNameItem);
    tb->setItem(nRow, 1, new QTableWidgetItem(artistName));

}

void SongList::wirteToTable(QTableWidget *tb)
{
    tb->setRowCount(size());
    tb->setColumnCount(2);
    for (int i = 0; i < size(); i++) {
        auto songNameItem = new QTableWidgetItem(at(i).songName);
        songNameItem->setData(Qt::UserRole, at(i).id);
        songNameItem->setData(Qt::UserRole + 1, at(i).url);
        tb->setItem(i, 0, songNameItem);
        tb->setItem(i, 1, new QTableWidgetItem(at(i).artistName));
    }
}

void SongList::appendToTable(QTableWidget *tb)
{
    for (auto &s : *this) {
        s.appendToTable(tb);
    }
}

QDataStream &operator<<(QDataStream &out, const Song &s){
    out << s.songName;
    out << s.artistName;
    out << s.url;
    out << s.id;
    out << s.lyric;
    return out;
}
QDataStream &operator>>(QDataStream &in,  Song &s){
    in >> s.songName;
    in >> s.artistName;
    in >> s.url;
    in >> s.id;
    in >> s.lyric;
    return in;
}
